package com.xingkeduo.business.operation.domain;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.xingkeduo.business.operation.service.*;
import com.xingkeduo.pojo.dto.Shops.*;
import com.xingkeduo.pojo.dto.Shops.shopsApi.*;
import com.xingkeduo.pojo.query.*;
import com.xingkeduo.pojo.remote.feign.*;
import com.xingkeduo.pojo.table.*;
import com.xingkeduo.pojo.vo.*;
import com.xingkeduo.tool.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xingkeduo.pojo.enums.ActivityEnum.ActivityModeEnum;
import com.xingkeduo.pojo.enums.ActivityEnum.ActivityTypeEnum;
import com.xingkeduo.pojo.enums.ActivityEnum.ActivityVoEnum;
import com.xingkeduo.pojo.enums.ActivityEnum.PreferentialModeEnum;
import com.xingkeduo.pojo.enums.ShopsStatus;
import com.xingkeduo.pojo.enums.ShopsType;
import com.xingkeduo.util.pojo.domain.Page;
import com.xingkeduo.util.pojo.enums.YesNoEnum;
import com.xingkeduo.util.pojo.exception.DataException;
import com.xingkeduo.util.tool.CommonUtil;
import com.xingkeduo.util.tool.IdentityUtil;

import static com.xingkeduo.tool.OperaConstants.IMG_DIR_ADDRESS;

/**
 * 商户domain
 *
 * @author wangxilong <wangxilong@xingkeduo.com>
 * @version id:v0.1 ${date}${time}
 * @package BeautyOS
 * @copyright Copyright (c) XKD 2019
 */
@Component
public class ShopsDomain {
	private static Logger log = LoggerFactory.getLogger(ShopsDomain.class);

    @Autowired
    private ShopsService shopsService;

    @Autowired
    private VendorService vendorService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private ShopsDaysService shopsDaysService;

    @Autowired
    private ManagerService managerService;


    @Autowired
    private ShopsServprodService shopsServprodService;

    @Autowired
    private PictureService pictureService;

    @Autowired
    private AdminFeignService adminFeignService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private CitiesService citiesService;
    @Autowired
    private CountryService countryService;
    @Autowired
    private CommentFeignService commentFeignService;
    @Autowired
    private WordPadFeignService wordPadFeignService;
    @Autowired
    private MarketingFeignService marketingFeignService;
    @Autowired
    private ServprodService servprodService;
    @Autowired
    private ShopUpdateLogService shopUpdateLogService;
    @Autowired
    private SystemConfigService systemConfigService;
    
    /**
     * 小程序根据相应信息获取店铺列表（含最近服务的一次店铺） pantong
     * @param f_user_id
     * @param longitude
     * @param latitude
     * @param cityId
     * @param offset
     * @param is_first
     * @param mobile_type
     * @return
     * @throws Throwable
     */
    public Map<String,Object> getShopsList(Long f_user_id, Double longitude, Double latitude, Long cityId, int offset, int is_first, String mobile_type)throws Throwable{
    	log.info("ShopsDomain.getShopsDetail 开始执行 f_user_id： " + f_user_id + " cityId: " + cityId + "  时间:"+new Date().getTime());
    	Map<String,Object> result = new HashMap<String,Object>();
    	result.put("limit", 5);//默认按5条一页查询    如果上次服务的店铺与当前的城市一致，则按5-1即4条分页查询（此时分页查询时要排除此店铺id）

    	if(cityId==null) {
    		cityId = 0L;
    	}

    	if(cityId.longValue()< 0L) {//城市id有问题
			return result;
		}
//    	else if(cityId.longValue() == 0L) {//默认根据经纬度定位最近店铺所在的城市
//			ShopsQuery sq = new ShopsQuery();
//			sq.setLatitude(latitude);
//			sq.setLongitude(longitude);
//			List<ShopsTableVo> sList = shopsService.selectVoListByShopsQuery(sq);
//			if(sList!=null && sList.size()>0 && sList.get(0).getCitiesId()!=null && sList.get(0).getCitiesId().longValue()>0L) {
//				cityId = sList.get(0).getCitiesId().longValue();
//			}
//		}
    	
    	//根据经纬度算province_id
    	if(longitude!=null && latitude!=null) {
    		ShopsQuery sq = new ShopsQuery();
    		sq.setLatitude(latitude);
    		sq.setLongitude(longitude);
    		List<ShopsTableVo> sList = shopsService.selectVoListByShopsQuery(sq);
    		if(sList!=null && sList.size()>0 && sList.get(0).getCitiesId()!=null && sList.get(0).getCitiesId().longValue()>0L) {
    			result.put("province_id",  sList.get(0).getCitiesId().longValue());
    			
    			if(cityId.longValue() == 0L){
    				cityId = sList.get(0).getCitiesId().longValue();
    			}
    		}
    	}
    	
    	
    	result.put("status", cityId);
    	
    	StringBuffer storeIds = new StringBuffer("");
    	//is_first为1时 根据城市id userid获取最近一次服务店铺  同时记录城市id到province_id中
    	boolean curCityHaveThisStore = false;
    	long nearStoreId = -1L;
    	boolean showSchoolFlag = false;//f_user_id是否是测试用户标记
    	String testUserIds = "";//测试用户ids
    	SystemConfigQuery systemConfigQuery = new SystemConfigQuery();
    	systemConfigQuery.setConfigKey("TEST_USERIDS");
    	List<SystemConfigTable> testUIdsList = systemConfigService.selectLists(systemConfigQuery);
    	if(testUIdsList!=null && testUIdsList.size()>0) {
    		testUserIds = testUIdsList.get(0).getConfigValue();
    	}
    	try {
	    	if(true) {//is_first == 1
	    		//result.put("province_id", cityId);
	    		if(f_user_id!=null && f_user_id.longValue()>0) {
	    			//判断f_user_id是否在测试用户id中
	    			if(StringUtils.isNotBlank(testUserIds) && testUserIds.indexOf(","+f_user_id.toString()+",")>=0) {
	    				showSchoolFlag = true;
	    			}
	    			
	    			log.info("ShopsDomain.getShopsList 获取上次服务店铺接口请求参数 f_user_id： " + f_user_id + " cityId: " + null);
	    			ResponseUtils responseUtils  = orderService.getCratfsmanShop(String.valueOf(f_user_id), null, "1");
	    	    	log.info("ShopsDomain.getShopsList 获取上次服务店铺接口返回信息 " + responseUtils==null? "":responseUtils.toString());
	        		if(responseUtils.success()) {
	        			String storeId = (String) responseUtils.getData();
	        			if(StringUtils.isNotEmpty(storeId)) {//获取最近服务的店铺
	        				storeIds.append(storeId+",");
	        				nearStoreId = Long.valueOf(storeId);
	        				ShopsQuery sq = new ShopsQuery();
	        				sq.setId(nearStoreId);
	//        				sq.setCitiesId(cityId);
	        				sq.setLongitude(longitude);
	        				sq.setLatitude(latitude);
	        				List<Integer> typeList = new ArrayList<Integer>();//店铺类型过滤   快剪学院 不展示
	        				typeList.add(ShopsType.DIRECT.getValue());
	        				typeList.add(ShopsType.DRMANGE.getValue());
	        				typeList.add(ShopsType.LEAGUE.getValue());
	        				if(showSchoolFlag) {
	        					typeList.add(ShopsType.SCHOOL.getValue());
	        				}
	        				sq.setTypeList(typeList);
	        				List<Integer> statusList = new ArrayList<Integer>();
	//        				statusList.add(ShopsStatus.INIT.getValue());
	        				statusList.add(ShopsStatus.HOT.getValue());
	        				statusList.add(ShopsStatus.OPEN.getValue());
	        				statusList.add(ShopsStatus.TEMPCLS.getValue());
	        				sq.setStatusList(statusList);
	        				List<ShopsTableVo> voList = shopsService.pageListVoByShopsQuery(sq);
	        				if(voList!=null && voList.size()>0) {
	        					//根据areaid获取区县名称
	        					if(voList.get(0).getAreaid()!=null) {
	        						CountryTable ct = countryService.selectById(voList.get(0).getAreaid().longValue());
	        						if(ct!=null && StringUtils.isNotEmpty(ct.getName())) {
	        							voList.get(0).setAreaName(ct.getName());
	        						}
	        					}
	        					result.put("last_service_store_record", voList.get(0));
	        					//如果当前店铺所在的城市与目前查询或者定位到的城市id一致，则按4页查询  下边查询分页时也要排除此店铺id
	        					if(voList.get(0)!=null && voList.get(0).getCitiesId()!=null &&  voList.get(0).getCitiesId().longValue() == cityId) {
	        						log.info("ShopsDomain.getShopsList 该店铺在当前城市  f_user_id： " + f_user_id + " nearStoreId: " + nearStoreId + " nearStoreCityId: " + voList.get(0).getCitiesId() + " curCityid: " + cityId);
	        						curCityHaveThisStore = true;
	        					}
	        				}
	        			}
	        		}
	    		}
	    	}
    	}catch (Exception e) {
			
		}

    	List<ShopsTableVo> list = new ArrayList<ShopsTableVo>();
    	//根据城市id等条件获取店铺列表  分页
    	if(offset<0) {
			offset = 0;
		}
		if(offset%4==0 || offset%5==0) {
			ShopsQuery sq = new ShopsQuery();
			sq.setRecordStart(offset);
			if(curCityHaveThisStore) {
				sq.setRecordEnd(4);
				sq.setDeleteStoreId(nearStoreId);
				result.put("limit", 4);
			}else {
				sq.setRecordEnd(5);
			}
			sq.setCitiesId(cityId);
			sq.setLongitude(longitude);
			sq.setLatitude(latitude);
			List<Integer> typeList = new ArrayList<Integer>();//店铺类型过滤   快剪学院 不展示
			typeList.add(ShopsType.DIRECT.getValue());
			typeList.add(ShopsType.DRMANGE.getValue());
			typeList.add(ShopsType.LEAGUE.getValue());
			if(showSchoolFlag) {
				typeList.add(ShopsType.SCHOOL.getValue());
			}
			sq.setTypeList(typeList);
			List<Integer> statusList = new ArrayList<Integer>();//店铺状态
//			statusList.add(ShopsStatus.INIT.getValue());
			statusList.add(ShopsStatus.HOT.getValue());
			statusList.add(ShopsStatus.OPEN.getValue());
			statusList.add(ShopsStatus.TEMPCLS.getValue());
			sq.setStatusList(statusList);
			List<ShopsTableVo> voList = shopsService.pageListVoByShopsQuery(sq);
			if(voList!=null && voList.size()>0) {
				for (int i = 0; i < voList.size(); i++) {
					ShopsTableVo vo = voList.get(i);
					
					storeIds.append(vo.getId()+",");
					
					//根据areaid获取区县名称
					if(vo.getAreaid()!=null) {
						CountryTable ct = countryService.selectById(vo.getAreaid().longValue());
						if(ct!=null && StringUtils.isNotEmpty(ct.getName())) {
							vo.setAreaName(ct.getName());
						}
					}

					//获取门店营业时间
		            ShopsDaysQuery shopsDaysQuery = new ShopsDaysQuery();
		            shopsDaysQuery.setShopsId(vo.getId());
		            List<ShopsDaysTable> shopsDaysTableList = shopsDaysService.selectLists(shopsDaysQuery);
		            if(shopsDaysTableList!=null && shopsDaysTableList.size()>0) {
		            	ShopsDaysTable sdTable = shopsDaysTableList.get(0);
		            	vo.setStartTime(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()) + " 10:00" );
    					vo.setEndTime(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()) + " 21:30");
    					if(sdTable!=null) {
    						if(StringUtils.isNotEmpty(sdTable.getStarttime())) {
    							vo.setStartTime(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()) + " " + sdTable.getStarttime());
    						}
    						if(StringUtils.isNotEmpty(sdTable.getEndtime())) {
    							vo.setEndTime(DateFormat.getDateInstance(DateFormat.MEDIUM).format(new Date()) + " " + sdTable.getEndtime());
    						}
    					}
		            }
		            
					if(vo.getId() == nearStoreId) {//如果是最近服务的店铺置顶展示
//						result.put("last_service_store_record", vo);
					}else {
						list.add(vo);
					}
				}
				
			}
		}
		log.info("ShopsDomain.getShopsList 该店铺在当前城市  f_user_id： " + f_user_id + " curCityid: " + cityId + " 返回的城市列表数量: " + (list==null? 0:list.size()));
		//获取活动标签
		if(storeIds!=null && storeIds.length()>1) {
			try {
				ResponseMessage responseMessage = marketingFeignService.getBatchStoreActivityDetail(storeIds.substring(0, storeIds.length()-1));
	    		if(responseMessage.getStatus()==1 && responseMessage.getData()!=null) {//有数据时
	    			Map<String, List<ActivityApiResponseVo>> mapList =  (Map<String, List<ActivityApiResponseVo>>) responseMessage.getData();
	    			if(mapList!=null && mapList.size()>0) {
	    				Map<Long,List<ActivityVo>> shopActivityMap = new HashMap<Long,List<ActivityVo>>();
		    				for (String key : mapList.keySet()) {
		    					if(StringUtils.isNotEmpty(key)) {
		    						List<ActivityApiResponseVo> activityList = mapList.get(key);
		    						if(activityList!=null && activityList.size()>0) {
		    							shopActivityMap.put(Long.valueOf(key), this.transferActivityApiResponseVoListToActivityVoList(activityList));
		    						}
		    					}
						}
		    				result.put("shopActivityTag", shopActivityMap);
	    			}
	    		}
			}catch (Exception e) {
				log.info("ShopsDomain.getShopsList获取店铺活动标签异常, storeIds: " + storeIds.substring(0, storeIds.length()-1));
				e.printStackTrace();
			}
		}
		
		result.put("store_list", list);

    	//获取可选城市列表
		CitiesQuery cq  = new CitiesQuery();
		cq.setStatus(1);
		List<CitiesTable> cList = citiesService.selectLists(cq);
		result.put("city", cList);
		log.info("ShopsDomain.getShopsList 结束执行 f_user_id： " + f_user_id + " cityId: " + cityId + "  时间:"+new Date().getTime());
    	return result;
    }

    
    /**
     * 将活动列表转换成活动标签列表  pantong  2019年5月14日上午10:13:21  
     * 规则：1.只取类型为门店活动  活动类型为支付活动、分流活动的
     *      2.返回的数据有四类：
     *         立减  短标签：立减xx元  满xx元减xx元   展开展示内容:活动名称 判断是否与券卡叠加
     *         折扣  短标签：xx折 满xx元xx折              展开展示内容:活动名称 判断是否与券卡叠加
     *         特价  短标签：特价xx元                          展开展示内容:活动名称  判断是否与券卡叠加
     *         低峰优惠   短标签：低峰优惠                   展开展示内容:活动名称 判断是否与券卡叠加
     * @param resVoList
     * @return
     * List<ActivityVo>
     */
    private List<ActivityVo> transferActivityApiResponseVoListToActivityVoList(List<ActivityApiResponseVo> resVoList){
    	List<ActivityVo> list = new ArrayList<ActivityVo>();
    	if(resVoList!=null && resVoList.size()>0) {
    		for (int i = 0; i < resVoList.size(); i++) {
    			ActivityApiResponseVo vo = JSON.parseObject(JSON.toJSONString(resVoList.get(i)),ActivityApiResponseVo.class);
				if(vo!=null && vo.getActivityMode()!=null && ActivityModeEnum.STORE.getCode()==vo.getActivityMode()
						&& (ActivityTypeEnum.PAYMENT.getStatusType().equals(vo.getActivityType()) 
								|| ActivityTypeEnum.BYPASS_FLOW.getStatusType().equals(vo.getActivityType()))) {
					if(ActivityTypeEnum.PAYMENT.getStatusType().equals(vo.getActivityType())) {//支付活动
						if(vo.getPreferentialMode()!=null && vo.getActivityAmount()!=null && vo.getActivityAmount().compareTo(BigDecimal.ZERO)>0) {
							if(PreferentialModeEnum.REDUCE.getCode() == vo.getPreferentialMode() ){//立减
								ActivityVo av = new ActivityVo();
								av.setType(ActivityVoEnum.Vertical_Reduction.getType());
								av.setTypeName(ActivityVoEnum.Vertical_Reduction.getTypeName());
								if(vo.getLeastCost()!=null && vo.getLeastCost().compareTo(BigDecimal.ZERO)>0) {
									av.setShotDesc("满" + vo.getLeastCost().stripTrailingZeros().toPlainString() + "元减" + vo.getActivityAmount().stripTrailingZeros().toPlainString() + "元");//
								}else {
									av.setShotDesc("立减"+vo.getActivityAmount().stripTrailingZeros().toPlainString()+"元");//
								}
								if(vo.getIsOverlying()!=null && vo.getIsOverlying() == 1) {//1叠加 默认不叠加
									av.setLongDesc(vo.getName());
								}else {
									av.setLongDesc(vo.getName()+"（不与券卡叠加）");
								}
								list.add(av);
							}else if (PreferentialModeEnum.DISCOUNT.getCode() == vo.getPreferentialMode()) {//折扣
								ActivityVo av = new ActivityVo();
								av.setType(ActivityVoEnum.Discount.getType());
								av.setTypeName(ActivityVoEnum.Discount.getTypeName());
								if(vo.getLeastCost()!=null && vo.getLeastCost().compareTo(BigDecimal.ZERO)>0) {
									av.setShotDesc("满" + vo.getLeastCost().stripTrailingZeros().toPlainString() + "元" + vo.getActivityAmount().multiply(BigDecimal.TEN).stripTrailingZeros().toPlainString() + "折");//
								}else {
									av.setShotDesc(vo.getActivityAmount().multiply(BigDecimal.TEN).stripTrailingZeros().toPlainString()+"折");//
								}
								if(vo.getIsOverlying()!=null && vo.getIsOverlying() == 1) {
									av.setLongDesc(vo.getName());
								}else {
									av.setLongDesc(vo.getName()+"（不与券卡叠加）");
								}
								list.add(av);
							}else if(PreferentialModeEnum.SPECIAL_OFFER.getCode() == vo.getPreferentialMode()) {//特价
								ActivityVo av = new ActivityVo();
								av.setType(ActivityVoEnum.OnSale.getType());
								av.setTypeName(ActivityVoEnum.OnSale.getTypeName());
								av.setShotDesc("特价"+vo.getActivityAmount().stripTrailingZeros().toPlainString()+"元");//
								av.setLongDesc(vo.getName());
//								if(vo.getIsOverlying()!=null && vo.getIsOverlying() == 1) {
//									av.setLongDesc(vo.getName());
//								}else {
//									av.setLongDesc(vo.getName()+"（不与券卡叠加）");
//								}
								list.add(av);
							}
						}
					}else if(ActivityTypeEnum.BYPASS_FLOW.getStatusType().equals(vo.getActivityType())) {//分流活动
						if(vo.getPreferentialMode()!=null && PreferentialModeEnum.REDUCE.getCode() == vo.getPreferentialMode()) {
							ActivityVo av = new ActivityVo();
							av.setType(ActivityVoEnum.LowPeak_Discount.getType());
							av.setTypeName(ActivityVoEnum.LowPeak_Discount.getTypeName());
							av.setShotDesc("低峰优惠");
							av.setLongDesc(vo.getName());
							list.add(av);
						}
					}
				}
			}
    	}
    	
    	return list;
    }
    
    
    /**
     * @desc：小程序 店铺详情       pantong  2019年5月9日下午1:44:33
     * @param f_user_id
     * @param longitude
     * @param latitude
     * @param shopId
     * @param time
     * @param token
     * @param mobile_type
     * @return
     * @throws Throwable
     * Map<String,Object>
     */
    public Map<String,Object> getShopsDetail(long f_user_id, Double longitude, Double latitude, Long shopId, String  time, String token, String mobile_type)throws Throwable{
    	Map<String,Object> result = new HashMap<String,Object>();
    	
    	if(shopId==null || shopId.longValue()<=0L) {
    		throw new Exception("店铺信息获取失败，请确认店铺id是否正常！");
    	}
    	
    	ShopsTableVo vo = new ShopsTableVo();//店铺基本信息
    	ShopsTable shopsTable = shopsService.selectById(shopId);
    	BeanUtils.copyProperties(shopsTable, vo);
    	
    	//营业周天
    	ShopsDaysQuery shopsDaysQuery = new ShopsDaysQuery();
        shopsDaysQuery.setShopsId(vo.getId());
        List<ShopsDaysTable> shopsDaysTableList = shopsDaysService.selectLists(shopsDaysQuery);
        if(shopsDaysTableList!=null && shopsDaysTableList.size()>0) {
        	ShopsDaysTable sdTable = shopsDaysTableList.get(0);
			//营业周天
        	if(StringUtils.isNotEmpty(sdTable.getDayids())) {
        		vo.setWeekDays(WeekUtil.convertWeek(sdTable.getDayids()));
        	}
        	vo.setStartTime(sdTable.getStarttime());
        	vo.setEndTime(sdTable.getEndtime());
        }
    	//店铺距离
    	if(longitude!=null && latitude!=null && StringUtils.isNotEmpty(vo.getLatitude()) && StringUtils.isNotEmpty(vo.getLongitude())) {
    		vo.setDistance(LocationUtils.getDistanceToM(latitude, longitude, Double.valueOf(vo.getLatitude()), Double.valueOf(vo.getLongitude())).doubleValue());
    	}
    	
    	//店铺活动标签
    	try {
	    	ResponseMessage storeResponseMessage = marketingFeignService.getStoreActivityDetail(vo.getId());
	    	log.info("ShopsDomain.getShopsDetail 获取店铺活动标签接口请求参数 f_user_id： " + f_user_id + " shopId: " + shopId);
	    	log.info("ShopsDomain.getShopsDetail 获取店铺活动标签接口返回信息 " + storeResponseMessage==null? "":storeResponseMessage.toString());
			if(storeResponseMessage.getStatus()==1 && storeResponseMessage.getData()!=null) {//有数据时
				List<ActivityApiResponseVo> voList = (List<ActivityApiResponseVo>) storeResponseMessage.getData();
				vo.setStoreActivityTag(this.transferActivityApiResponseVoListToActivityVoList(voList));
			}
    	}catch (Exception e) {
			log.info("ShopsDomain.getShopsDetail 获取店铺活动标签异常,f_user_id:" + f_user_id + " shopId: " + shopId);
    		e.printStackTrace();
		}
    	
    	//未付款订单号 -- 柴华接口
    	String order_no = "";
    	log.info("ShopsDomain.getShopsDetail 获取未付款订单号接口请求参数 f_user_id： " + f_user_id + " shopId: " + shopId);
    	ResponseUtils noPayOrderRes  = orderService.getNopayOrderNo(String.valueOf(f_user_id), "1");
    	log.info("ShopsDomain.getShopsDetail 获取未付款订单号接口返回信息 " + noPayOrderRes==null? "":noPayOrderRes.toString());
		if(noPayOrderRes.success()) {
			order_no = (String) noPayOrderRes.getData();
		}
    	result.put("order_no", order_no);
    	//是否是上次剪发门店 -- 柴华
    	boolean nextFlag = false;
    	try {
    		log.info("ShopsDomain.getShopsDetail 是否是上次剪发门店接口请求参数 f_user_id： " + f_user_id + " shopId: " + shopId);
    		ResponseUtils nextserverShopRes = orderService.isLastServerShops(String.valueOf(f_user_id), String.valueOf(shopId), "1");
	    	log.info("ShopsDomain.getShopsDetail 是否是上次剪发门店接口返回信息 " + nextserverShopRes==null? "":nextserverShopRes.toString());
			if(nextserverShopRes.success()) {
				nextFlag = (Boolean) nextserverShopRes.getData();
			}
    	}catch (Exception e) {
    		log.info("ShopsDomain.getShopsDetail 判断是否是上次剪发门店异常,f_user_id:" + f_user_id + " shopId: " + shopId);
    		e.printStackTrace();
		} 
    	result.put("is_last_service", nextFlag);
    	//最近一次五星带图评论  -- 柴华
    	result.put("count", 0);//默认0时，不展示评论
    	try {
    		log.info("ShopsDomain.getShopsDetail 店铺评论信息接口请求参数 f_user_id： " + f_user_id);
	    	ResponseReviewUtils commentRes = commentFeignService.getCommentDetail(String.valueOf(shopId), "1");
	    	log.info("ShopsDomain.getShopsDetail 店铺评论信息接口返回信息 " + commentRes==null? "":commentRes.toString());
	    	if(commentRes.success()) {
	    		result.put("count", commentRes.getReviews());//好评数
	    		Map comment = (Map) commentRes.getData();//最近好评信息
	    		if(comment!=null) {
	    			Boolean anonymous = (Boolean) comment.get("anonymous");//是否匿名 true匿名
	    			if(anonymous!=null && !anonymous) {
	    				if(comment.get("userId")!=null) {
		    				Long userId = Long.valueOf(comment.get("userId").toString());//用户id\
		    				log.info("ShopsDomain.getShopsDetail 评论对应的用户信息接口请求参数 f_user_id： " + f_user_id);
			    			ResponseUtils responseUtils  = adminFeignService.getBasicUserInfo(userId, time, token, mobile_type);
			    	    	log.info("ShopsDomain.getShopsDetail 评论对应的用户信息接口返回信息 " + responseUtils==null? "":responseUtils.toString());
			    			String userName = "";//用户昵称
			    			String avatar = "";//头像
			    			if(responseUtils!=null && responseUtils.success()) {
			    				Map map = (Map) responseUtils.getData();
			    				if(map!=null) {
			    					userName = map.get("f_name")==null? "":map.get("f_name").toString();
			    					avatar = map.get("f_avatar")==null? "":map.get("f_avatar").toString();
			    				}
			    			}
			    			result.put("user_name", userName);
			    			result.put("f_avatar", avatar);
		    			}
	    			}else {
	    				result.put("user_name", "匿名星粉");
	    				result.put("f_avatar", "");
	    			}
	    				
	    		}
	    		result.put("comment", comment);
	    	}
    	}catch (Exception e) {
    		log.info("ShopsDomain.getShopsDetail 获取最近一次带图五星评论信息异常, shopId: " + shopId);
    		e.printStackTrace();
		}
    	
    	//各服务及对应的价格  -- 夕桐、子峰 
    	//1.获取该门店配置的服务类型列表及对应的价格  老系统服务类型和服务表的id一致 故不需要做转换
    	//2.遍历当前门店的服务类型，获取该门店当前服务下 当天可约或者 当天不可约时最近可约 发型师的最低价，如果没可约，取该门店价格
    	//2.1 根据门店id获取该店铺下所有可约发型师及最早可约时间
    	//2.2 根据门店id + 发型师ids + 服务id  获取提供当前服务的所有发型师id name 及服务价格
    	//2.3 封装对象（发型师id、可约最早时间（具体到年月日）、价格） 对象实现compare方法   然后放到List中，排序。排序规则：时间相等  价格低的靠前，时间不相等  时间小的靠前。
//    	shopId = 69L;
    	//获取各服务及对应的名字 描述
    	Map<Long,ServprodTable> servprodMap = new HashMap<Long,ServprodTable>();
    	ServprodQuery servprodQuery = new ServprodQuery();
    	servprodQuery.setIsDelete(YesNoEnum.NO);
    	List<ServprodTable> servprodList = servprodService.selectLists(servprodQuery);
    	if(servprodList!=null && servprodList.size()>0) {
    		for (int i = 0; i < servprodList.size(); i++) {
    			servprodMap.put(servprodList.get(i).getId(), servprodList.get(i));
			}
    	}
    	
    	//存放店铺各服务信息 
    	List<ServprodVo> shopServprodList = new ArrayList<ServprodVo>();
    	ShopsServprodQuery shopsServprodQuery = new ShopsServprodQuery();
    	shopsServprodQuery.setShopsId(shopId);
    	shopsServprodQuery.setIsDelete(YesNoEnum.NO);
    	//店铺服务列表
    	List<ShopsServprodTable> serviceList = shopsServprodService.selectLists(shopsServprodQuery);
    	if(serviceList!=null && serviceList.size()>0) {
    		//店铺可约发型师及其最早可约时间
    		List<StockWorkTimeVo> storeStaffVos = null;
    		Map<Long,String> storeStaffDate = new HashMap<Long,String>();
    		log.info("ShopsDomain.getShopsDetail 获取店铺下发型师及最早可约时间接口请求参数 shopId： " + shopId);
        	ResponseMessage responseMessage = wordPadFeignService.getMinFreeStockByStoreIdOfStaffStock(shopId, "");
	    	log.info("ShopsDomain.getShopsDetail 获取店铺下发型师及最早可约时间接口返回信息 " + responseMessage==null? "":responseMessage.toString());
    		if(responseMessage.getStatus()==1 && responseMessage.getData()!=null) {//有数据时
    			storeStaffVos = JSON.parseArray(JSON.toJSONString(responseMessage.getData()), StockWorkTimeVo.class);
    		}
    		StringBuffer crafttsmanIds = new StringBuffer("");
    		if(storeStaffVos!=null && storeStaffVos.size()>0) {//获取可约发型师id集合
    			for (int i = 0; i < storeStaffVos.size(); i++) {
    				if(storeStaffVos.get(i).getStaffId()!=null && StringUtils.isNotEmpty(storeStaffVos.get(i).getNearlyAppointmentDateFormat())) {
    					crafttsmanIds.append(storeStaffVos.get(i).getStaffId() + ",");
    					storeStaffDate.put(storeStaffVos.get(i).getStaffId(), storeStaffVos.get(i).getNearlyAppointmentDateFormat());
    				}
				}
    		}
    		Map<Long,BigDecimal> serviceShopPrice = new HashMap<Long,BigDecimal>();//服务-店铺价格
    		for (int i = 0; i < serviceList.size(); i++) {
    			if(serviceList.get(i)!=null && serviceList.get(i).getServprodId()!=null && serviceList.get(i).getPrice()!=null) {
    				ServprodVo servprodVo = new  ServprodVo();
    				servprodVo.setServiceId(serviceList.get(i).getServprodId());
    				servprodVo.setPrice(BigDecimal.valueOf(serviceList.get(i).getPrice()).setScale(0, RoundingMode.DOWN));
    				servprodVo.setActivityContent("");
    				servprodVo.setNew(false);
    				ServprodTable servprodTable = servprodMap.get(serviceList.get(i).getServprodId());
    				if(servprodTable!=null) {
    					servprodVo.setName(StringUtils.isNotEmpty(servprodTable.getName())? servprodTable.getName():"");
    					servprodVo.setDesc(StringUtils.isNotEmpty(servprodTable.getIntro())? servprodTable.getIntro():"");
    				}
    				//单位分
    				serviceShopPrice.put(serviceList.get(i).getServprodId(), BigDecimal.valueOf(serviceList.get(i).getPrice()).setScale(0, RoundingMode.DOWN));
    				List<CraftsmanServiceTO> craftsmanServiceTOList = null;//所有可约的
    				if(crafttsmanIds!=null && crafttsmanIds.toString().length()>1) {//可约发型师id不为空，则取查询crafttsmanIds下是否提供此服务及提供此服务时是否配置了调价
    					//获取店铺可约发型师craftsmanIds下提供某个服务的发型师列表信息及调价价格（调价价格可能为0或者null 此时取店铺价格）
    					log.info("ShopsDomain.getShopsDetail 获取店铺suk下发型师及价格接口请求参数 shopId： " + shopId + " skuId:" + serviceList.get(i).getServprodId());
        				ResponseUtils responseUtils = adminFeignService.listCraftsmanInfoByShopIdAndServiceId(shopId, serviceList.get(i).getServprodId(), crafttsmanIds.toString().substring(0, crafttsmanIds.toString().length()-1));
        		    	log.info("ShopsDomain.getShopsDetail 获取店铺suk下发型师及价格接口返回信息 " + responseUtils==null? "":responseUtils.toString());
        				if(responseUtils!=null && responseUtils.success()) {//获取成功时
        					craftsmanServiceTOList = JSON.parseArray(JSON.toJSONString(responseUtils.getData()), CraftsmanServiceTO.class);
        					if(craftsmanServiceTOList!=null && craftsmanServiceTOList.size()>0) {
        						for (int j = craftsmanServiceTOList.size()-1; j >= 0; j--) {
        							if(craftsmanServiceTOList.get(j).getCraftsmanId()==null 
        									//|| craftsmanServiceTOList.get(j).getPrices()==null
        									|| storeStaffDate.get(craftsmanServiceTOList.get(j).getCraftsmanId())==null) {
        								craftsmanServiceTOList.remove(j);
        							}else {
        								if(craftsmanServiceTOList.get(j).getPrices()==null || BigDecimal.ZERO.compareTo(craftsmanServiceTOList.get(j).getPrices())==0) {//发型师价格为空，则该发型师去店铺价格
        									BigDecimal shopPrice = serviceShopPrice.get(serviceList.get(i).getServprodId());//单位分
        									craftsmanServiceTOList.get(j).setPrices(shopPrice.divide(BigDecimal.valueOf(100L)));
        								}
        								craftsmanServiceTOList.get(j).setNearlyAppointmentDate(storeStaffDate.get(craftsmanServiceTOList.get(j).getCraftsmanId()));
        							}
        						}
        					}
        				}
    				}
    				
    				if(craftsmanServiceTOList!=null && craftsmanServiceTOList.size()>0) {//如果有可约发型师 则该sku的价格为可约发型师最低价
    					Collections.sort(craftsmanServiceTOList);
    					//BigDecimal shopPrice = serviceShopPrice.get(serviceList.get(i).getServprodId());//单位分
    					//if(shopPrice!=null && shopPrice.compareTo(craftsmanServiceTOList.get(0).getPrices().multiply(BigDecimal.valueOf(100L)))>0) {//单位是元 -- 转分后对比
    						serviceShopPrice.put(serviceList.get(i).getServprodId(),craftsmanServiceTOList.get(0).getPrices().multiply(BigDecimal.valueOf(100L)).setScale(0, RoundingMode.DOWN));
    						servprodVo.setPrice(craftsmanServiceTOList.get(0).getPrices().multiply(BigDecimal.valueOf(100L)).setScale(0, RoundingMode.DOWN));
    					//}
    				}
    				shopServprodList.add(servprodVo);
    			}
			}
    		result.put("serviceShopPrice", serviceShopPrice);
    	}
    	Collections.sort(shopServprodList);
    	vo.setShopServprodList(shopServprodList);//店铺sku列表
    	result.put("datailVo", vo);
    	return result;
    }
    
    
    /**
     * 根据店铺id获取各sku的最低价   pantong  2019年5月30日上午10:45:21
     * 最低价规则：
     * 5.如果当日有发型师可约，则显示该sku当日可约的最低发型师价格
	 * 6.如果当日没有发型师可约，则显示该sku最近可约当天的发型师最低价格
	 * 6.5如果没有可约的发型师，则显示店铺sku价格
     * @param shopId
     * @return
     * @throws Throwable
     * List<ServprodVo>
     */
    public List<ServprodVo> getStoreSkuInfoListByStoreId(Long shopId) throws Throwable{
    	//获取各服务及对应的名字 描述
    	Map<Long,ServprodTable> servprodMap = new HashMap<Long,ServprodTable>();
    	ServprodQuery servprodQuery = new ServprodQuery();
    	servprodQuery.setIsDelete(YesNoEnum.NO);
    	List<ServprodTable> servprodList = servprodService.selectLists(servprodQuery);
    	if(servprodList!=null && servprodList.size()>0) {
    		for (int i = 0; i < servprodList.size(); i++) {
    			servprodMap.put(servprodList.get(i).getId(), servprodList.get(i));
			}
    	}
    	//存放店铺各服务信息 
    	List<ServprodVo> shopServprodList = new ArrayList<ServprodVo>();
    	ShopsServprodQuery shopsServprodQuery = new ShopsServprodQuery();
    	shopsServprodQuery.setShopsId(shopId);
    	shopsServprodQuery.setIsDelete(YesNoEnum.NO);
    	//店铺服务列表
    	List<ShopsServprodTable> serviceList = shopsServprodService.selectLists(shopsServprodQuery);
    	if(serviceList!=null && serviceList.size()>0) {
    		//店铺可约发型师及其最早可约时间
    		List<StockWorkTimeVo> storeStaffVos = null;
    		Map<Long,String> storeStaffDate = new HashMap<Long,String>();
    		log.info("ShopsDomain.getStoreSkuInfoListByStoreId 获取店铺下发型师及最早可约时间接口请求参数 shopId： " + shopId);
        	ResponseMessage responseMessage = wordPadFeignService.getMinFreeStockByStoreIdOfStaffStock(shopId, "");
	    	log.info("ShopsDomain.getStoreSkuInfoListByStoreId 获取店铺下发型师及最早可约时间接口返回信息 " + responseMessage==null? "":responseMessage.toString());
    		if(responseMessage.getStatus()==1 && responseMessage.getData()!=null) {//有数据时
    			storeStaffVos = JSON.parseArray(JSON.toJSONString(responseMessage.getData()), StockWorkTimeVo.class);
    		}
    		StringBuffer crafttsmanIds = new StringBuffer("");
    		if(storeStaffVos!=null && storeStaffVos.size()>0) {//获取发型师id集合
    			for (int i = 0; i < storeStaffVos.size(); i++) {
    				if(storeStaffVos.get(i).getStaffId()!=null && StringUtils.isNotEmpty(storeStaffVos.get(i).getNearlyAppointmentDateFormat())) {
    					crafttsmanIds.append(storeStaffVos.get(i).getStaffId() + ",");
    					storeStaffDate.put(storeStaffVos.get(i).getStaffId(), storeStaffVos.get(i).getNearlyAppointmentDateFormat());
    				}
				}
    		}
    		Map<Long,BigDecimal> serviceShopPrice = new HashMap<Long,BigDecimal>();//服务-店铺价格
    		for (int i = 0; i < serviceList.size(); i++) {
    			if(serviceList.get(i)!=null && serviceList.get(i).getServprodId()!=null && serviceList.get(i).getPrice()!=null) {
    				ServprodVo servprodVo = new  ServprodVo();
    				servprodVo.setServiceId(serviceList.get(i).getServprodId());
    				servprodVo.setPrice(BigDecimal.valueOf(serviceList.get(i).getPrice()).setScale(0, RoundingMode.DOWN));
    				servprodVo.setActivityContent("");
    				servprodVo.setNew(false);
    				ServprodTable servprodTable = servprodMap.get(serviceList.get(i).getServprodId());
    				if(servprodTable!=null) {
    					servprodVo.setName(StringUtils.isNotEmpty(servprodTable.getName())? servprodTable.getName():"");
    					servprodVo.setDesc(StringUtils.isNotEmpty(servprodTable.getIntro())? servprodTable.getIntro():"");
    				}
    				//单位分
    				serviceShopPrice.put(serviceList.get(i).getServprodId(), BigDecimal.valueOf(serviceList.get(i).getPrice()).setScale(0, RoundingMode.DOWN));
    				List<CraftsmanServiceTO> craftsmanServiceTOList = null;//所有可约的
    				if(crafttsmanIds!=null && crafttsmanIds.toString().length()>1) {//可约发型师id不为空，则取查询crafttsmanIds下是否提供此服务及提供此服务时是否配置了调价
    					//获取店铺可约发型师craftsmanIds下提供某个服务的发型师列表信息及调价价格（调价价格可能为0或者null 此时取店铺价格）
    					log.info("ShopsDomain.getStoreSkuInfoListByStoreId 获取店铺suk下发型师及价格接口请求参数 shopId： " + shopId + " skuId:" + serviceList.get(i).getServprodId());
    					ResponseUtils responseUtils = adminFeignService.listCraftsmanInfoByShopIdAndServiceId(shopId, serviceList.get(i).getServprodId(), crafttsmanIds.toString().substring(0, crafttsmanIds.toString().length()-1));
        		    	log.info("ShopsDomain.getStoreSkuInfoListByStoreId 获取店铺suk下发型师及价格接口返回信息 " + responseUtils==null? "":responseUtils.toString());
        				if(responseUtils!=null && responseUtils.success()) {//获取成功时
        					craftsmanServiceTOList = JSON.parseArray(JSON.toJSONString(responseUtils.getData()), CraftsmanServiceTO.class);
        					if(craftsmanServiceTOList!=null && craftsmanServiceTOList.size()>0) {
        						for (int j = craftsmanServiceTOList.size()-1; j >= 0; j--) {
        							if(craftsmanServiceTOList.get(j).getCraftsmanId()==null 
        									//|| craftsmanServiceTOList.get(j).getPrices()==null
        									|| storeStaffDate.get(craftsmanServiceTOList.get(j).getCraftsmanId())==null) {
        								craftsmanServiceTOList.remove(j);
        							}else {
        								if(craftsmanServiceTOList.get(j).getPrices()==null || BigDecimal.ZERO.compareTo(craftsmanServiceTOList.get(j).getPrices())==0) {//发型师价格为空，则该发型师去店铺价格
        									BigDecimal shopPrice = serviceShopPrice.get(serviceList.get(i).getServprodId());//单位分
        									craftsmanServiceTOList.get(j).setPrices(shopPrice.divide(BigDecimal.valueOf(100L)));
        								}
        								craftsmanServiceTOList.get(j).setNearlyAppointmentDate(storeStaffDate.get(craftsmanServiceTOList.get(j).getCraftsmanId()));
        							}
        						}
        					}
        				}
    				}
    				
    				if(craftsmanServiceTOList!=null && craftsmanServiceTOList.size()>0) {//如果有可约发型师 则该sku的价格为可约发型师最低价
    					Collections.sort(craftsmanServiceTOList);
    					//BigDecimal shopPrice = serviceShopPrice.get(serviceList.get(i).getServprodId());//单位分
    					//if(shopPrice!=null && shopPrice.compareTo(craftsmanServiceTOList.get(0).getPrices().multiply(BigDecimal.valueOf(100L)))>0) {//单位是元 -- 转分后对比
    						serviceShopPrice.put(serviceList.get(i).getServprodId(),craftsmanServiceTOList.get(0).getPrices().multiply(BigDecimal.valueOf(100L)).setScale(0, RoundingMode.DOWN));
    						servprodVo.setPrice(craftsmanServiceTOList.get(0).getPrices().multiply(BigDecimal.valueOf(100L)).setScale(0, RoundingMode.DOWN));
    					//}
    				}
    				shopServprodList.add(servprodVo);
    			}
			}
    	}
    	return shopServprodList;
    }
    
    public ShopsDetailLogDTO getShopsById(Long id) throws Throwable {
        ShopsDetailLogDTO shopsDetailLogDTO = new ShopsDetailLogDTO();
        ShopsTable shopsTable = shopsService.selectById(id);
        List<ShopsDaysDTO> shopsDaysListTemp = new ArrayList<>();

        List<ShopsServprodDTO> shopsServprodListTemp = new ArrayList<>();

        if(!CommonUtil.isEmpty(shopsTable)){
            //获取门店营业时间
            ShopsDaysQuery shopsDaysQuery = new ShopsDaysQuery();
            shopsDaysQuery.setShopsId(id);
            List<ShopsDaysTable> shopsDaysTableList = shopsDaysService.selectLists(shopsDaysQuery);
            if(!CommonUtil.isEmpty(shopsDaysTableList) && shopsDaysTableList.size() > 0){
                for (ShopsDaysTable shopsDaysTable : shopsDaysTableList) {
                    ShopsDaysDTO shopsDaysDTO = new ShopsDaysDTO();
                    BeanUtils.copyProperties(shopsDaysTable,shopsDaysDTO);
                    if(!CommonUtil.isEmpty(shopsDaysTable.getDayids())){
                        String weekName = WeekUtil.convertWeek(shopsDaysTable.getDayids());
                        shopsDaysDTO.setDayids(shopsDaysTable.getDayids());
                        shopsDaysDTO.setDayName(weekName);
                    }
                    shopsDaysListTemp.add(shopsDaysDTO);
                }
            }

            //获取门店配置
            ShopsServprodQuery shopsServprodQuery = new ShopsServprodQuery();
            shopsServprodQuery.setShopsId(id);
            List<ShopsServprodTable> shopsServprodTableList = shopsServprodService.selectLists(shopsServprodQuery);
            if(!CommonUtil.isEmpty(shopsServprodTableList) && shopsServprodTableList.size() > 0){
                for (ShopsServprodTable shopsServprodTable : shopsServprodTableList) {
                    ShopsServprodDTO covert = ShopsServprodDTO.covert(shopsServprodTable);
                    shopsServprodListTemp.add(covert);
                }
            }

        }

        BeanUtils.copyProperties(shopsTable,shopsDetailLogDTO);
        List<String> shoptag = JSONObject.parseArray(shopsTable.getShoptag(),String.class);
        shopsDetailLogDTO.setShoptag(shoptag);

        List<ImgDTO> shopImg = new ArrayList<>();
        if(!CommonUtil.isEmpty(shopsTable.getShopsImgids())){
            String[] split = shopsTable.getShopsImgids().split(",");
            for (String s : split) {
                PictureTable pictureTable =  pictureService.selectById(Long.valueOf(s));
                ImgDTO imgDTO = new ImgDTO();
                imgDTO.setId(String.valueOf(pictureTable.getId()));
                imgDTO.setOssId(pictureTable.getOssId());
                imgDTO.setPicDir(IMG_DIR_ADDRESS+pictureTable.getPicDir());
                shopImg.add(imgDTO);
            }
            shopsDetailLogDTO.setShopImg(shopImg);
        }
        if(!CommonUtil.isEmpty(shopsDetailLogDTO.getCreatedBy())){
            ManagerTable managerTable = managerService.selectById(shopsDetailLogDTO.getCreatedBy());
            if(!CommonUtil.isEmpty(managerTable)){
                shopsDetailLogDTO.setCreatedByName(managerTable.getName());
            }
        }
        shopsDetailLogDTO.setCreateTimes(DateTimeUtils.yyyy_MM_dd_HH_mmToDate(shopsDetailLogDTO.getCreatedTime()));
        shopsDetailLogDTO.setDaysList(shopsDaysListTemp);
        shopsDetailLogDTO.setShopsServprodList(shopsServprodListTemp);

        //店铺图片暂时写死
//        if(!CommonUtil.isEmpty(shopsDetailLogDTO.getStatus())){
//            if(shopsDetailLogDTO.getStatus() == 0 || shopsDetailLogDTO.getStatus() == 1){
//                shopsDetailLogDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/coming_soon.png");
//            }else if(shopsDetailLogDTO.getStatus() == 2){
//                shopsDetailLogDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/store_img.png");
//            }else{
//                shopsDetailLogDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/reform_coming_soon.png");
//            }
//        }
        //用户接口获取店铺下员工总经理信息
        JSONObject shopid = new JSONObject();
        shopid.put("shopid",id);
        ResponseUtils <CraftsmanShopDTO> craftsmanShopInfo = adminFeignService.getCraftsmanShopInfo(shopid.toString());

        log.info("店铺下员工总经理信息",craftsmanShopInfo);
        if(craftsmanShopInfo != null && craftsmanShopInfo.success()){
            shopsDetailLogDTO.setCraftsmanInfo(craftsmanShopInfo.getData());
        }
        //这里搞一下日志
        List<ShopUpdateLogDTO> shopUpdateLogDTOS = new ArrayList<>();
        List<ShopUpdateLogTable> shopUpdateLogTablesList = shopUpdateLogService.selectShopUpdateLogs(new ShopUpdateLogQuery().setShopId(id));
        if(!CommonUtil.isEmpty(shopUpdateLogTablesList)){

            for (ShopUpdateLogTable shopUpdateLogTable : shopUpdateLogTablesList) {
                ShopUpdateLogDTO shopUpdateLogDTO = new ShopUpdateLogDTO();
                BeanUtils.copyProperties(shopUpdateLogTable,shopUpdateLogDTO);

                String name = "";
                if(shopUpdateLogTable.getStatus() == 0 && !CommonUtil.isEmpty(shopUpdateLogTable.getCreatedBy())){
                    ManagerTable managerTable = managerService.selectById(shopUpdateLogTable.getCreatedBy());
                     name = managerTable.getName();
                    shopUpdateLogDTO.setCreateByName(name);
                    String CreateTime = DateTimeUtils.yyyy_MM_dd_HH_mmToDate(shopUpdateLogTable.getCreatedTime());
                    shopUpdateLogDTO.setCreateTime(CreateTime);
                }else{
                    ManagerTable managerTable = managerService.selectById(shopUpdateLogTable.getUpdatedBy());
                    name = managerTable.getName();
                    shopUpdateLogDTO.setUpdateByName(name);
                    String UpdateTime = DateTimeUtils.yyyy_MM_dd_HH_mmToDate(shopUpdateLogTable.getUpdatedTime());
                    shopUpdateLogDTO.setUpdateTime(UpdateTime);
                }
                shopUpdateLogDTOS.add(shopUpdateLogDTO);
            }
        }
        shopsDetailLogDTO.setShopStatusLog(shopUpdateLogDTOS);
        log.info("店铺详情信息",shopsDetailLogDTO);
        return shopsDetailLogDTO;
    }
    //获取店铺短信息
    public ShopsResponseDTO getShopsSortInfo(Long id) throws Throwable {
        ShopsResponseDTO shopsResponseDTO = new ShopsResponseDTO();
        if(CommonUtil.isEmpty(id)){
            throw new DataException(DataException.Type.DEFAULT, "店铺ID不能为空");
        }
        ShopsTable shopsTable = shopsService.selectById(id);
        if(CommonUtil.isEmpty(shopsTable)){
            throw new DataException(DataException.Type.DEFAULT, "店铺信息不存在");
        }
        shopsResponseDTO.setId(id);
        shopsResponseDTO.setName(shopsTable.getName());

        List<ShopsServprodTable> shopsServprodTables = shopsServprodService.selectLists(new ShopsServprodQuery().setShopsId(id));

        if(!CommonUtil.isEmpty(shopsServprodTables)){
            List<ShopsServprodDTO> shopsServprodListTemp = new ArrayList<>();
            for (ShopsServprodTable shopsServprodTable : shopsServprodTables) {
                ShopsServprodDTO covert = ShopsServprodDTO.covert(shopsServprodTable);
                shopsServprodListTemp.add(covert);
            }
            shopsResponseDTO.setShopsServprodList(shopsServprodListTemp);
        }
        return shopsResponseDTO;
    }

    //API门店详情
    public ShopsApiDTO getShopsApiById(Long id ,String craftsmanid) throws Throwable {
        ShopsApiDTO shopsApiDTO = new ShopsApiDTO();
        ShopsTable shopsTable = shopsService.selectById(id);
        List<ShopsDaysApiDTO> shopsDaysListTemp = new ArrayList<>();
        List<ShopsServprodDTO> shopsServprodListTemp = new ArrayList<>();
        List<Integer> grain = new ArrayList<>();

        if(!CommonUtil.isEmpty(shopsTable)){
            //获取门店营业时间
            ShopsDaysQuery shopsDaysQuery = new ShopsDaysQuery();
            shopsDaysQuery.setShopsId(id);
            List<ShopsDaysTable> shopsDaysTableList = shopsDaysService.selectLists(shopsDaysQuery);
            if(!CommonUtil.isEmpty(shopsDaysTableList) && shopsDaysTableList.size() > 0){
                for (ShopsDaysTable shopsDaysTable : shopsDaysTableList) {
                    ShopsDaysApiDTO shopsDaysApiDTO = new ShopsDaysApiDTO();
                    BeanUtils.copyProperties(shopsDaysTable,shopsDaysApiDTO);
                    if(!CommonUtil.isEmpty(shopsDaysTable.getDayids())){
                        String weekName = WeekUtil.convertWeek(shopsDaysTable.getDayids());
                        shopsDaysApiDTO.setDayName(weekName);
                    }
                    shopsDaysListTemp.add(shopsDaysApiDTO);
                }
            }
            //获取门店配置
            ShopsServprodQuery shopsServprodQuery = new ShopsServprodQuery();
            shopsServprodQuery.setShopsId(id);
            List<ShopsServprodTable> shopsServprodTableList = shopsServprodService.selectLists(shopsServprodQuery);
            if(!CommonUtil.isEmpty(shopsServprodTableList) && shopsServprodTableList.size() > 0){
                for (ShopsServprodTable shopsServprodTable : shopsServprodTableList) {
                    ShopsServprodDTO covert = ShopsServprodDTO.covert(shopsServprodTable);
                    shopsServprodListTemp.add(covert);
                    grain.add(shopsServprodTable.getServtime());
                }

            }
        }
        BeanUtils.copyProperties(shopsTable,shopsApiDTO);

        List<String> shoptag = JSONObject.parseArray(shopsTable.getShoptag(),String.class);
       if(!CommonUtil.isEmpty(shoptag)){
           shopsApiDTO.setShoptag(shoptag);
       }
        if(!CommonUtil.isEmpty(shopsApiDTO.getVendorId())){
            VendorTable vendorTable = vendorService.selectById(shopsTable.getVendorId());
            if(!CommonUtil.isEmpty(vendorTable.getName())){
                shopsApiDTO.setVendorName(vendorTable.getName());
            }
        }
        //店铺图片，暂时写死
//        if(!CommonUtil.isEmpty(shopsTable.getShopsimgid())){
//
//            PictureTable pictureTable =  pictureService.selectById(shopsTable.getShopsimgid());
//            shopsApiDTO.setShopsImg(pictureTable.getPicDir());
//        } shopsApiDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/coming_soon.png");
        if(!CommonUtil.isEmpty(shopsApiDTO.getStatus())){

            if(shopsApiDTO.getTerminal() == 2){
                shopsApiDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/box_store_img.png");
            }else{
                if(shopsApiDTO.getStatus() == 0 || shopsApiDTO.getStatus() == 1){
                    shopsApiDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/coming_soon.png");
                }else if(shopsApiDTO.getStatus() == 2){
                    shopsApiDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/store_img.png");
                }else{
                    shopsApiDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/reform_coming_soon.png");
                }
            }
        }

        shopsApiDTO.setGrainMax(MySortUtils.max1(grain));
        shopsApiDTO.setDaysList(shopsDaysListTemp);
        shopsApiDTO.setShopsServprodList(shopsServprodListTemp);
        //查询店铺下绑定的发型师
            JSONObject shopid = new JSONObject();
            shopid.put("shopid",id);
            JSONObject craftsmanids = new JSONObject();
            craftsmanids.put("craftsmanid",craftsmanid);
            String boundShop = "";
            try {
                boundShop = adminFeignService.getCratfsmanShop(craftsmanids.toString(),shopid.toString());
                log.info("API查看店铺信心请求用户查询经理店员信息返回参数:{}", boundShop);
            }catch (Throwable e){

        }
        if(!CommonUtil.isEmpty(boundShop)){

            JSONObject craftsmanidInfo = JSON.parseObject(boundShop);

            if(craftsmanidInfo.getOrDefault("status","0").toString().equals("1")){
                Object data = craftsmanidInfo.get("data");

                Object name = JSON.parseObject(data.toString()).get("name");

                String[] s = name.toString().split(" ");

                List<String> stringList = Arrays.asList(s);
                shopsApiDTO.setCraftsmanidInfo(stringList);
             }
            }
        shopsApiDTO.setStatusName(ShopsStatus.get(shopsApiDTO.getStatus()).getDesc());

        return shopsApiDTO;
    }

    /**
     * 小程序店铺详情后来删除
     * @return
     * @throws Throwable
     */
    public ShopsApiDTO getShopsApiByIds(Long id) throws Throwable {
        ShopsApiDTO shopsApiDTO = new ShopsApiDTO();
        ShopsTable shopsTable = shopsService.selectById(id);

        List<ShopsDaysApiDTO> shopsDaysListTemp = new ArrayList<>();
        List<ShopsServprodDTO> shopsServprodListTemp = new ArrayList<>();
        List<Integer> grain = new ArrayList<>();

        if(!CommonUtil.isEmpty(shopsTable)){
            //获取门店营业时间
            ShopsDaysQuery shopsDaysQuery = new ShopsDaysQuery();
            shopsDaysQuery.setShopsId(id);
            List<ShopsDaysTable> shopsDaysTableList = shopsDaysService.selectLists(shopsDaysQuery);
            if(!CommonUtil.isEmpty(shopsDaysTableList) && shopsDaysTableList.size() > 0){
                for (ShopsDaysTable shopsDaysTable : shopsDaysTableList) {
                    ShopsDaysApiDTO shopsDaysApiDTO = new ShopsDaysApiDTO();
                    BeanUtils.copyProperties(shopsDaysTable,shopsDaysApiDTO);
                    if(!CommonUtil.isEmpty(shopsDaysTable.getDayids())){
                        String weekName = WeekUtil.convertWeek(shopsDaysTable.getDayids());
                        shopsDaysApiDTO.setDayName(weekName);
                    }
                    shopsDaysListTemp.add(shopsDaysApiDTO);
                }
            }
            //获取门店配置
            ShopsServprodQuery shopsServprodQuery = new ShopsServprodQuery();
            shopsServprodQuery.setShopsId(id);
            List<ShopsServprodTable> shopsServprodTableList = shopsServprodService.selectLists(shopsServprodQuery);
            if(!CommonUtil.isEmpty(shopsServprodTableList) && shopsServprodTableList.size() > 0){
                for (ShopsServprodTable shopsServprodTable : shopsServprodTableList) {
                    ShopsServprodDTO covert = ShopsServprodDTO.covert(shopsServprodTable);
                    shopsServprodListTemp.add(covert);
                    grain.add(shopsServprodTable.getServtime());
                }
            }
        }
        BeanUtils.copyProperties(shopsTable,shopsApiDTO);
        List<String> shoptag = JSONObject.parseArray(shopsTable.getShoptag(),String.class);
        shopsApiDTO.setShoptag(shoptag);

        if(!CommonUtil.isEmpty(shopsApiDTO.getVendorId())){
            VendorTable vendorTable = vendorService.selectById(shopsTable.getVendorId());
            shopsApiDTO.setVendorName(vendorTable.getName());
        }
        //店铺图片，暂时写死
//        if(!CommonUtil.isEmpty(shopsTable.getShopsimgid())){
//
//            PictureTable pictureTable =  pictureService.selectById(shopsTable.getShopsimgid());
//            shopsApiDTO.setShopsImg(pictureTable.getPicDir());
//        }

        if(!CommonUtil.isEmpty(shopsApiDTO.getStatus())){
            if(shopsApiDTO.getTerminal() == 2){
                shopsApiDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/box_store_img.png");
            }else{
                if(shopsApiDTO.getStatus() == 0 || shopsApiDTO.getStatus() == 1){
                    shopsApiDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/coming_soon.png");
                }else if(shopsApiDTO.getStatus() == 2){
                    shopsApiDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/store_img.png");
                }else{
                    shopsApiDTO.setShopsImg("http://mcdn.xingkeduo.com/image/bos/store/reform_coming_soon.png");
                }
            }
        }
        shopsApiDTO.setGrainMax(MySortUtils.max1(grain));
        shopsApiDTO.setStatusName(ShopsStatus.get(shopsApiDTO.getStatus()).getDesc());

        shopsApiDTO.setDaysList(shopsDaysListTemp);
        shopsApiDTO.setShopsServprodList(shopsServprodListTemp);
        return shopsApiDTO;
    }
    //获取库存颗粒
    public ShopsGrainApiDTO getShopsGrain(Long id) throws Throwable {
        List<ShopsDaysApiDTO> shopsDaysApiDTOS = new ArrayList<>();
        List<Integer> grain = new ArrayList<>();
        ShopsGrainApiDTO shopsGrainApiDTO = new ShopsGrainApiDTO();
        ShopsTable shopsTable = shopsService.selectById(id);

        if (!CommonUtil.isEmpty(shopsTable)) {

            //获取门店营业时间
            ShopsDaysQuery shopsDaysQuery = new ShopsDaysQuery();
            shopsDaysQuery.setShopsId(id);
            List<ShopsDaysTable> shopsDaysTableList = shopsDaysService.selectLists(shopsDaysQuery);
            if (!CommonUtil.isEmpty(shopsDaysTableList) && shopsDaysTableList.size() > 0) {
                for (ShopsDaysTable shopsDaysTable : shopsDaysTableList) {
                    ShopsDaysApiDTO shopsDaysApiDTO = new ShopsDaysApiDTO();
                    BeanUtils.copyProperties(shopsDaysTable, shopsDaysApiDTO);
                    if (!CommonUtil.isEmpty(shopsDaysTable.getDayids())) {
                        String weekName = WeekUtil.convertWeek(shopsDaysTable.getDayids());
                        shopsDaysApiDTO.setDayName(weekName);
                    }
                    shopsDaysApiDTOS.add(shopsDaysApiDTO);
                }
                shopsGrainApiDTO.setParticle(shopsTable.getParticle());
            }

            //获取门店配置最高库存颗粒
            ShopsServprodQuery shopsServprodQuery = new ShopsServprodQuery();
            shopsServprodQuery.setShopsId(id);
            List<ShopsServprodTable> shopsServprodTableList = shopsServprodService.selectLists(shopsServprodQuery);
            List<Integer> grainList = new ArrayList<>();
            grainList.add(20);
            if(!CommonUtil.isEmpty(shopsServprodTableList) && shopsServprodTableList.size() > 0){
                for (ShopsServprodTable shopsServprodTable : shopsServprodTableList) {
                    grain.add(shopsServprodTable.getServtime());
                }
                List<Integer> integers = MySortUtils.max1(grain);
                if(integers == null || integers.size() == 0){
                    shopsGrainApiDTO.setGrainMax(grainList);
                }else{
                    shopsGrainApiDTO.setGrainMax(integers);
                }
            }else{
                shopsGrainApiDTO.setGrainMax(grainList);
            }
            shopsGrainApiDTO.setDaysList(shopsDaysApiDTOS);
            shopsGrainApiDTO.setSeatNum(shopsTable.getSeatnum());

        }else{
            throw new DataException(DataException.Type.DEFAULT, "店铺ID不存在，请确认!");
        }

        return shopsGrainApiDTO;
    }

    public List<ShopsTable> getShopsList(ShopsQuery shopsQuery) throws Throwable {

        List<ShopsTable> shopsList = shopsService.selectLists(shopsQuery);

        return shopsList;
    }

    public List<ShopsTable> getShopsApiList(ShopsQuery shopsQuery) throws Throwable {

        List<ShopsTable> shopsList = shopsService.selectLists(shopsQuery);

        return shopsList;
    }

    /**
     *获取店铺列表
     * @param shopsQuery
     * @return
     * @throws Throwable
     */

    public List<ShopsTable> doGetShopsList(ShopsQuery shopsQuery) throws Throwable {
//        if(shopsQuery.getStatusList() == null && shopsQuery.getStatus() == null){
//            shopsQuery.setStatus(Long.valueOf(ShopsStatus.OPEN.getValue()));
//        }

        List<ShopsTable> shopsList = shopsService.selectLists(shopsQuery);

        return shopsList;
    }

    /**
     *返回1.预热中2.开业中 3.临时闭店的状态列表，不返回 0.已创建和 4.已撤店
     */

    public List<ShopsStatusApiDTO> doGetShopsStatusList(ShopsQuery shopsQuery) throws Throwable {

        ArrayList<ShopsStatusApiDTO> shopsStatusApiDTOS = new ArrayList<>();

        ArrayList<Integer> status= Lists.newArrayList(1,2,3);

        List<ShopsTable> shopsList = shopsService.selectLists(new ShopsQuery().setStatusList(status));

        if(!CommonUtil.isEmpty(shopsList)){
            for (ShopsTable shopsTable : shopsList) {
                ShopsStatusApiDTO shopsStatusApiDTO = new ShopsStatusApiDTO();
                BeanUtils.copyProperties(shopsTable, shopsStatusApiDTO);
                shopsStatusApiDTOS.add(shopsStatusApiDTO);
            }
        }
        return shopsStatusApiDTOS;
    }






    //分页查询
    public Page<ShopsDTO> getShopsPageList(ShopsQuery shopsQuery) throws Throwable {
        Integer pageNo = shopsQuery.getPageNo();
        Integer pageSize = shopsQuery.getPageSize();
        Page<ShopsTable> shopsTablePage = shopsService.selectPageLists(shopsQuery,pageNo,pageSize);

        List<ShopsTable> dtoList = shopsTablePage.getDtoList();
        ArrayList<ShopsDTO> shopsDTOS = new ArrayList<>();

        if(!CommonUtil.isEmpty(dtoList)){
            for (ShopsTable shopsTable : dtoList) {

                ShopsDTO shopsDTO = new ShopsDTO();
                BeanUtils.copyProperties(shopsTable,shopsDTO);
                VendorTable vendorTable = vendorService.selectById(shopsTable.getVendorId());
                if(!CommonUtil.isEmpty(vendorTable)){
                    shopsDTO.setVendorName(vendorTable.getName());
                }
                ShopsDaysQuery shopsDaysQuery = new ShopsDaysQuery();
                shopsDaysQuery.setShopsId(shopsTable.getId());
                List<ShopsDaysTable> shopsDaysTableList = shopsDaysService.selectLists(shopsDaysQuery);
                if (!CommonUtil.isEmpty(shopsDaysTableList) && shopsDaysTableList.size() > 0) {
                    List<ShopsDaysDTO> shopsDaysDTOS = new ArrayList<>();
                    for (ShopsDaysTable shopsDaysTable : shopsDaysTableList) {
                        ShopsDaysDTO shopsDaysDTO = new ShopsDaysDTO();
                        BeanUtils.copyProperties(shopsDaysTable, shopsDaysDTO);
                        if (!CommonUtil.isEmpty(shopsDaysTable.getDayids())) {
                            String weekName = WeekUtil.convertWeek(shopsDaysTable.getDayids());
                            shopsDaysDTO.setDayName(weekName);

                        }
                        shopsDaysDTOS.add(shopsDaysDTO);
                    }
                    shopsDTO.setDaysList(shopsDaysDTOS);
                }

                //用户接口获取店铺下员工总经理信息
                JSONObject shopid = new JSONObject();
                shopid.put("shopid",shopsTable.getId());
                ResponseUtils <CraftsmanShopDTO> craftsmanShopInfo = adminFeignService.getCraftsmanShopInfo(shopid.toString());
                log.info("CMS分页查询查看店铺列表请求用户查询经理店员信息返回参数:{}", JSON.toJSONString(craftsmanShopInfo));
                if(craftsmanShopInfo != null && craftsmanShopInfo.success()){
                    shopsDTO.setCraftsmanInfo(craftsmanShopInfo.getData());
                }
                shopsDTOS.add(shopsDTO);

            }

        }

        Page<ShopsDTO> shopsDTOPage = new Page<>(pageNo,pageSize);

        BeanUtils.copyProperties(shopsTablePage, shopsDTOPage);
        shopsDTOPage.setDtoList(shopsDTOS);

        return shopsDTOPage;

    }
///随便测试搞一下
    @Transactional
    public int createShops(ShopsDTO shopsDTO) throws Throwable {

        if(!CommonUtil.isEmpty(shopsDTO.getName())){
            List<ShopsTable> shopsTableList = shopsService.selectLists(new ShopsQuery().setNameRepeat(shopsDTO.getName()));
            if(!CommonUtil.isEmpty(shopsTableList)){
                throw new DataException(DataException.Type.DEFAULT, "店铺名字不能重复，请更换重试！");
            }
        }
        //添加分公司,及相关信息
        if(!CommonUtil.isEmpty(shopsDTO.getOfficeId())){
            OfficeTable officeTable = officeService.selectById(shopsDTO.getOfficeId());
            if(!CommonUtil.isEmpty(officeTable)){
                shopsDTO.setVendorId(officeTable.getVendorId());
                shopsDTO.setCitiesId(officeTable.getCitiesId());
                shopsDTO.setCitiesName(officeTable.getCitiesName());
                shopsDTO.setOfficeName(officeTable.getName());
            }
        }
        //插入门店图片
        ArrayList<String> shopImgId = new ArrayList<>();
        List<ImgDTO> shopImg = shopsDTO.getShopImg();
        for (ImgDTO imgDTO : shopImg) {

            PictureTable pictureTable = new PictureTable();
            pictureTable.setOssId(imgDTO.getOssId()).setPicDir(imgDTO.getPicDir()).setPicType(1);
            int insert = pictureService.insert(pictureTable);
            shopImgId.add(String.valueOf(pictureTable.getId()));
        }
        ShopsTable shopsTable = new ShopsTable();
        shopsDTO.setShopsImgids(StringUtils.join(shopImgId, ","));
        BeanUtils.copyProperties(shopsDTO,shopsTable);
        String shopTag = JSON.toJSONString(shopsDTO.getShoptag());
        shopsTable.setShoptag(shopTag);
        if(CommonUtil.isEmpty(shopsTable.getParticle())){
            shopsTable.setParticle(String.valueOf(20));
        }
        int shopsId = shopsService.insert(shopsTable);
        ShopUpdateLogTable shopUpdateLogTable = new ShopUpdateLogTable();
        shopUpdateLogTable.setStatus(0)
                .setShopId(shopsTable.getId())
                .setCreatedBy(shopsTable.getCreatedBy());
        if(shopsId > 0){
            shopUpdateLogService.insert(shopUpdateLogTable);
        }
        List<ShopsDaysDTO> daysLists = shopsDTO.getDaysList();
        List<ShopsDaysTable> shopsDaysTableTemp = new ArrayList<>();
        //设置门店营业时间
       if(!CommonUtil.isEmpty(daysLists) && daysLists.size() > 0){
            for (ShopsDaysDTO shopsDaysDTO : daysLists) {
                ShopsDaysTable shopsDaysTable = new ShopsDaysTable();
                String shopsDaysStr = JSON.toJSON(shopsDaysDTO.getDayids()).toString();
                shopsDaysTable.setShopsId((long)shopsTable.getId());
                shopsDaysTable.setDayids(shopsDaysStr)
                        .setCode(IdentityUtil.nextId(IdentityUtil.Worker.USER))
                        .setDaytype(shopsDaysDTO.getDaytype())
                        .setStarttime(shopsDaysDTO.getStarttime())
                        .setEndtime(shopsDaysDTO.getEndtime());
//                shopsDaysService.insert(shopsDaysTable);
                shopsDaysTableTemp.add(shopsDaysTable);

                StoreWorkPlanDTO storeWorkPlanDTO = new StoreWorkPlanDTO();
                storeWorkPlanDTO.setStoreId(shopsTable.getId());
                storeWorkPlanDTO.setStoreCode(shopsTable.getCode());
                storeWorkPlanDTO.setMorningShiftEndTime(shopsDaysDTO.getEndtime());
                storeWorkPlanDTO.setMorningShiftStartTime(shopsDaysDTO.getStarttime());
                storeWorkPlanDTO.setNightShiftStartTime(shopsDaysDTO.getStarttime());
                storeWorkPlanDTO.setNightShiftEndTime(shopsDaysDTO.getEndtime());
                storeWorkPlanDTO.setAllDayShiftStartTime(shopsDaysDTO.getStarttime());
                storeWorkPlanDTO.getAllDayShiftEndTime();

                ResponseUtils storeGrain = wordPadFeignService.getStoreGrain(storeWorkPlanDTO);
            }
            shopsDaysService.insertAll(shopsDaysTableTemp);
        }


        return shopsId;
    }

    @Transactional
    public int modifyShops(ShopsDTO shops) throws Throwable {
        ShopsTable shopsTable1 = shopsService.selectById(shops.getId());
        if(CommonUtil.isEmpty(shopsTable1)){
            throw new DataException(DataException.Type.DEFAULT, "未找到此店铺，数据错误");
        }
        ShopUpdateLogTable shopUpdateLogTable = new ShopUpdateLogTable();
        if(!CommonUtil.isEmpty(shops.getStatus())){
            OfficeTable officeTable = officeService.selectById(shopsTable1.getOfficeId());
            if(officeTable.getStatus() ==2){
                throw new DataException(DataException.Type.DEFAULT, "该店铺对应的分公司处于禁用状态,无法更改店铺状态!");
            }
            shopUpdateLogTable.setStatus(shops.getStatus())
                            .setShopId(shops.getId())
                            .setUpdatedBy(shops.getUpdatedBy());
        }

        if(!CommonUtil.isEmpty(shops.getName())){
            if(!shops.getName().equals(shopsTable1.getName())){
                if(!CommonUtil.isEmpty(shops.getName())){
                    List<ShopsTable> shopsTableList = shopsService.selectLists(new ShopsQuery().setNameRepeat(shops.getName()));
                    if(!CommonUtil.isEmpty(shopsTableList)){
                        throw new DataException(DataException.Type.DEFAULT, "店铺名字已经存在");
                    }
                }
            }
        }

        //添加分公司,及相关信息
        if(!CommonUtil.isEmpty(shops.getOfficeId())){
            OfficeTable officeTable = officeService.selectById(shops.getOfficeId());
            if(!CommonUtil.isEmpty(officeTable)){
                shops.setVendorId(officeTable.getVendorId());
                shops.setCitiesId(officeTable.getCitiesId());
                shops.setCitiesName(officeTable.getCitiesName());
                shops.setOfficeName(officeTable.getName());
            }
        }
        ShopsTable shopsTable = new ShopsTable();

        List<ShopsDaysDTO> daysLists = shops.getDaysList();
        //设置门店营业时间
        if(!CommonUtil.isEmpty(daysLists) && daysLists.size() > 0){
            ShopsDaysQuery shopsDaysQuery = new ShopsDaysQuery();
            shopsDaysQuery.setShopsId(shops.getId());
            for (ShopsDaysDTO shopsDaysDTO : daysLists) {
                ShopsDaysTable shopsDaysTable = new ShopsDaysTable();
                //String shopsDaysStr = JSON.toJSON().toString();
                shopsDaysTable.setShopsId(shops.getId())
                        .setDayids(shopsDaysDTO.getDayids())
                        .setDaytype(shopsDaysDTO.getDaytype())
                        .setStarttime(shopsDaysDTO.getStarttime())
                        .setEndtime(shopsDaysDTO.getEndtime());

                shopsDaysQuery.setDaytype(shopsDaysDTO.getDaytype());
                List<ShopsDaysTable> shopsDaysTableList = shopsDaysService.selectLists(shopsDaysQuery);
                if(!CommonUtil.isEmpty(shopsDaysTableList) && shopsDaysTableList.size() > 0){
                    shopsDaysService.update(shopsDaysTable);

                }else{
                    shopsDaysService.insert(shopsDaysTable);
                }
            }
        }
        if(null != shopsTable1 && !CommonUtil.isEmpty(shopsTable1.getShopsImgids())){
        String[] split = shopsTable1.getShopsImgids().split(",");
        //老的图片
          List<String> oldShopImgOssId = new ArrayList<>();
          for (String ss : split) {
              PictureTable getOldPicOssId = pictureService.selectById(Long.valueOf(ss));
              oldShopImgOssId.add(getOldPicOssId.getOssId());
          }
        //新的OssId
          List<String> newShopImgOssId = new ArrayList<>();
        //插入门店图片
        ArrayList<String> shopImgId = new ArrayList<>();
        List<ImgDTO> shopImg = shops.getShopImg();

        for (ImgDTO imgDTO1 : shopImg) {
          newShopImgOssId.add(imgDTO1.getOssId());
         }
        if(!CheckDiffListUtils.getDiffrent(oldShopImgOssId,newShopImgOssId)){
            for (ImgDTO imgDTO : shopImg) {
                PictureTable pictureTable = new PictureTable();
                pictureTable.setOssId(imgDTO.getOssId()).setPicDir(imgDTO.getPicDir()).setPicType(1);
                int insert = pictureService.insert(pictureTable);
                shopImgId.add(String.valueOf(pictureTable.getId()));
            }
            shops.setShopsImgids(StringUtils.join(shopImgId, ","));
            //删除之前的图片

            for (String s : split) {
                PictureTable pictureTable1 = new PictureTable();
                pictureTable1.setId(Long.valueOf(s))
                        .setIsDelete(YesNoEnum.YES);

                pictureService.update(pictureTable1);
            }
        }

      }else{
            //插入门店图片
        ArrayList<String> shopImgId = new ArrayList<>();
        List<ImgDTO> shopImg = shops.getShopImg();
        if(!CommonUtil.isEmpty(shopImg)){
            for (ImgDTO imgDTO : shopImg) {

                PictureTable pictureTable = new PictureTable();
                pictureTable.setOssId(imgDTO.getOssId()).setPicDir(imgDTO.getPicDir()).setPicType(1);
                int insert = pictureService.insert(pictureTable);
                shopImgId.add(String.valueOf(pictureTable.getId()));
            }
            shops.setShopsImgids(StringUtils.join(shopImgId, ","));
        }

        }

        BeanUtils.copyProperties(shops,shopsTable);
        if(!CommonUtil.isEmpty(shops.getShoptag())){
            String shopTag = JSON.toJSONString(shops.getShoptag());
            shopsTable.setShoptag(shopTag);
        }
        int count = shopsService.update(shopsTable);

         if(count > 0 && !CommonUtil.isEmpty(shops.getStatus())){
            shopUpdateLogService.insert(shopUpdateLogTable);
        }
        return count;
    }

    public ShopsScreenInfoDTO getShopsScreenInfo(Long id) throws Throwable {

        ShopsScreenInfoDTO shopsScreenInfoDTO = new ShopsScreenInfoDTO();

        if(CommonUtil.isEmpty(id)){
            throw new DataException(DataException.Type.DEFAULT, "店铺ID不能为空");
        }
        shopsScreenInfoDTO.setStoreId(id);
        ShopsTable shopsTable = shopsService.selectById(id);
        if(CommonUtil.isEmpty(shopsTable)){
            throw new DataException(DataException.Type.DEFAULT, "未找到店铺信息");
        }
        shopsScreenInfoDTO.setStoreName(shopsTable.getName());

        List<ShopsDaysTable> shopsDaysTables = shopsDaysService.selectLists(new ShopsDaysQuery().setShopsId(id));
        if(CommonUtil.isEmpty(shopsDaysTables)){
            throw new DataException(DataException.Type.DEFAULT, "未配置店铺营业时间");
        }

            shopsScreenInfoDTO.setStarttime(shopsDaysTables.get(0).getStarttime());
            shopsScreenInfoDTO.setEndtime(shopsDaysTables.get(0).getEndtime());


        return shopsScreenInfoDTO;

    }

        //删除
    public int delShops(Long id) throws Throwable {

            JSONObject shopid = new JSONObject();
            shopid.put("shopid",id);
            String boundShop = "";
            boundShop = adminFeignService.getHaveCratfsmanShop(shopid.toString());
            if(!CommonUtil.isEmpty(boundShop)){
                JSONObject craftsmanidInfo = JSON.parseObject(boundShop);
                    Object data = craftsmanidInfo.get("data");
                    Object count =  JSON.parseObject(data.toString()).get("id");
                   if(Integer.valueOf(String.valueOf(count))>0){
                       throw new DataException(DataException.Type.DEFAULT, "该店铺下有绑定的发型师,无法删除店铺!");
                   }
            }

        ShopsTable shopsTable = new ShopsTable();

        shopsTable.setId(id);
        shopsTable.setIsDelete(YesNoEnum.YES);
        int delRes = shopsService.delete(shopsTable);
        if(delRes > 0){
            return delRes;
        }else{
            throw new DataException(DataException.Type.FAIL, "删除失败");
        }
    }


    public Long getCityId(Long id) throws Throwable {

        if(CommonUtil.isEmpty(id)){
            throw new DataException(DataException.Type.DEFAULT, "店铺ID不能为空");
        }
        ShopsTable shopsTable = shopsService.selectById(id);
        if(CommonUtil.isEmpty(shopsTable)){
            throw new DataException(DataException.Type.DEFAULT, "此店铺不存在");
        }
        if(CommonUtil.isEmpty(shopsTable.getCitiesId())){
            throw new DataException(DataException.Type.DEFAULT, "店铺未绑定城市,请前往配置");
        }
        Long citiesId = shopsTable.getCitiesId();
        return citiesId;
    }


    public SeeShopIdVo getLongitudeAndLatitudeShopInfo(Double latitude , Double longitude,Long userId) throws Throwable {

        if(CommonUtil.isEmpty(latitude) || CommonUtil.isEmpty(latitude)||CommonUtil.isEmpty(latitude)){
            throw new DataException(DataException.Type.DEFAULT, "请求参数不能为空");
        }

        ShopsQuery shopsQuery = new ShopsQuery();
        shopsQuery.setLatitude(latitude)
                .setLongitude(longitude);
        String testUserIds = "";//测试用户ids
        SystemConfigQuery systemConfigQuery = new SystemConfigQuery();
        systemConfigQuery.setConfigKey("TEST_USERIDS");
        List<SystemConfigTable> testUIdsList = systemConfigService.selectLists(systemConfigQuery);
        if(testUIdsList!=null && testUIdsList.size()>0) {
            testUserIds = testUIdsList.get(0).getConfigValue();
        }
        List<Integer> typeList = new ArrayList<Integer>();//店铺类型过滤   快剪学院 不展示
        typeList.add(ShopsType.DIRECT.getValue());
        typeList.add(ShopsType.DRMANGE.getValue());
        typeList.add(ShopsType.LEAGUE.getValue());
        if(StringUtils.isNotBlank(testUserIds) && testUserIds.indexOf(","+ userId.toString() +",")>=0) {
            typeList.add(ShopsType.SCHOOL.getValue());
        }
        shopsQuery.setTypeList(typeList);
        SeeShopIdVo shopsTableVo = shopsService.selectByShopsId(shopsQuery);

        return shopsTableVo;
    }



}
